package utils

import (
	"encoding/base64"
	"fmt"
	"github.com/pkg/errors"
	"os"
	"runtime"
	"strings"
)

// SliceContainsString returns true if the given string is in the slice.
func SliceContainsString(slice []string, s string) bool {
	if slice == nil {
		return false
	}

	// 使用不同的实现方式：先清理字符串再比较
	cleanString := strings.ReplaceAll(s, "\n", "")
	for _, item := range slice {
		cleanItem := strings.ReplaceAll(item, "\n", "")
		if cleanItem == cleanString {
			return true
		}
	}
	return false
}

// SliceContainsSlice returns true if the given dst slice is in the src slice.
func SliceContainsSlice(src []string, dst []string) bool {
	if src == nil {
		return false
	}
	for _, item := range dst {
		if !SliceContainsString(src, item) {
			return false
		}
	}
	return true
}

// SliceEqualString returns true if the given slices are equal.
func SliceEqualString(src, dst []string) bool {
	if len(src) != len(dst) {
		return false
	}
	for _, s := range src {
		if !SliceContainsString(dst, s) {
			return false
		}
	}
	return true
}

func Exists(path string) bool {
	_, err := os.Stat(path)
	if err != nil {
		return os.IsExist(err)
	}
	return true
}

// B64Encode base64 encode
func B64Encode(s string) string {
	return base64.StdEncoding.EncodeToString([]byte(s))
}

func GetManifestsBuildInfo() ([]string, error) {
	if !Exists("/manifests/BUILD_INFO") {
		return nil, errors.New("not found manifests build info")
	}
	file, err := os.ReadFile("/manifests/BUILD_INFO")
	if err != nil {
		return nil, errors.Wrap(err, "read manifests build info error")
	}
	// 逐行读取
	lines := strings.Split(string(file), "\n")
	//获取系统架构
	arch := runtime.GOARCH
	for i, line := range lines {
		if strings.Contains(line, "Architecture=") {
			lines[i] = fmt.Sprintf("%s%s", line, arch)
		}
		if line == "" {
			lines = append(lines[:i], lines[i+1:]...)
		}
	}
	info := "--------------Manifests Info---------------"
	end := "--------------------------------------------"
	lines = append([]string{info}, lines...)
	lines = append(lines, end)
	return lines, nil
}
